import sqlite3
from typing import List
from model.Book import Book
from common.Env import Env

dbPath = Env.getDBPath()


class BookDao:
    def list(self) -> List[Book]:
        try:
            conn = sqlite3.connect(dbPath)
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM books")
            rows = cursor.fetchall()

            books = []
            for row in rows:
                book = {"title": row[1], "author": row[2], "price": row[3]}
                books.append(book)

            conn.close()
            return books
        except sqlite3.Error as e:
            print(f"Database error:{e}")
            return []

    def add(self, book: Book):
        try:
            conn = sqlite3.connect(dbPath)
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO books (title, author, price) VALUES (?,?,?)",
                (book.title, book.author, book.price),
            )
            conn.commit()
            conn.close()
        except sqlite3.Error as e:
            print(f"Database error:{e}")
            return []
